/*
 * SPDX-FileCopyrightText: 2024 Andrew Gunnerson
 * SPDX-License-Identifier: GPL-3.0-only
 */

package com.sanji.audio_test.rule

import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.sanji.audio_test.rule.RecordRulesAdapter.CustomViewHolder

/**
 * 录音规则触摸帮助回调类
 * 用于处理录音规则列表项的拖拽和滑动操作
 * @param adapter 录音规则适配器
 */
internal class RecordRulesTouchHelperCallback(private val adapter: RecordRulesAdapter) :
    ItemTouchHelper.SimpleCallback(
        ItemTouchHelper.UP or ItemTouchHelper.DOWN,  // 允许上下拖拽
        ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT,  // 允许左右滑动
    ) {
    
    /**
     * 处理拖拽移动操作
     * @param recyclerView RecyclerView实例
     * @param viewHolder 源ViewHolder
     * @param target 目标ViewHolder
     * @return 是否处理成功
     */
    override fun onMove(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder,
    ): Boolean {
        adapter.onRuleMove(viewHolder.bindingAdapterPosition, target.bindingAdapterPosition)
        return true
    }

    /**
     * 处理滑动操作（移除项目）
     * @param viewHolder 被滑动的ViewHolder
     * @param direction 滑动方向
     */
    override fun onSwiped(
        viewHolder: RecyclerView.ViewHolder,
        direction: Int,
    ) = adapter.onRuleRemove(viewHolder.bindingAdapterPosition)

    /**
     * 判断是否可以放置到目标位置
     * @param recyclerView RecyclerView实例
     * @param current 当前ViewHolder
     * @param target 目标ViewHolder
     * @return 是否可以放置
     */
    override fun canDropOver(
        recyclerView: RecyclerView,
        current: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder,
    ): Boolean {
        // 不允许移动到非自定义ViewHolder上
        if (target !is CustomViewHolder) {
            return false
        }

        // 防止将项目移动到默认规则所在位置
        return !adapter.isDefaultRule(target.bindingAdapterPosition)
    }

    /**
     * 获取移动标志
     * @param recyclerView RecyclerView实例
     * @param viewHolder ViewHolder
     * @return 移动标志
     */
    override fun getMovementFlags(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
    ): Int {
        // 不允许移动非自定义ViewHolder
        if (viewHolder !is CustomViewHolder) {
            return makeMovementFlags(0, 0)
        }

        // 防止移动或删除默认规则
        if (adapter.isDefaultRule(viewHolder.bindingAdapterPosition)) {
            return makeMovementFlags(0, 0)
        }

        return super.getMovementFlags(recyclerView, viewHolder)
    }
}